<template>
  <div class="index-container">
    <!-- 主布局 -->
    <div class="main-layout">
      <!-- 侧边栏 -->
      <div class="sidebar" :class="{ 'collapsed': sidebarCollapsed }">
        <!-- Logo区域 -->
        <div class="logo-section">
          <div class="logo-icon">
            <div class="car-icon">🚗</div>
          </div>
          <h1 class="logo-text" v-show="!sidebarCollapsed">MES玩具小车制造系统</h1>
        </div>

        <!-- Element Plus 菜单 -->
        <el-menu :default-active="activeMenu" class="el-menu-vertical" background-color="transparent"
          text-color="#333333" active-text-color="#1890ff" :unique-opened="true" :collapse="sidebarCollapsed" router
          @open="handleSubMenuOpen" @close="handleSubMenuClose">
          <!-- 仪表盘 -->
          <el-menu-item index="DashboardView">
            <el-icon>
              <Clock />
            </el-icon>
            <template #title>仪表盘(胡辉)</template>
          </el-menu-item>

          <!-- 基础数据 -->
          <el-sub-menu index="DashboardView">
            <template #title>
              <el-icon>
                <Box />
              </el-icon>
              <span>基础数据</span>
            </template>

            <!-- 工厂建模 -> 基础数据 -->
            <el-sub-menu index="factoryModeling">
              <template #title>
                <el-icon>
                  <OfficeBuilding />
                </el-icon>
                <span>工厂建模</span>
              </template>
              <el-menu-item index="/CheJian">车间管理（胡辉）</el-menu-item>
              <el-menu-item index="/ChanXian">产线管理（胡辉）</el-menu-item>
              <el-menu-item index="/Customer">客户管理（胡辉）</el-menu-item>
            </el-sub-menu>

            <!-- 在基础数据菜单下添加供应商管理 -->
            <!-- 物料管理 -->
            <el-sub-menu index="materialManagement">
              <template #title>
                <el-icon>
                  <PriceTag />
                </el-icon>
                <span>物料管理</span>
              </template>
              <el-menu-item index="/MaterialGroup">物料群组（胡辉）</el-menu-item>
              <el-menu-item index="/MaterialProduct">产品物料（胡辉）</el-menu-item>
              <el-menu-item index="/bom">BOM（王文杰）</el-menu-item>
            </el-sub-menu>
            <el-menu-item index="/Supplier"><el-icon>
                <PhoneFilled />
              </el-icon>供应商管理（胡辉）</el-menu-item>
          </el-sub-menu>

          <!-- 工艺管理 -->
          <el-sub-menu index="processManagement">
            <template #title>
              <el-icon>
                <Opportunity />
              </el-icon>
              <span>工艺管理</span>
            </template>
            <el-menu-item index="/process-maintenance">工序维护（曾庆优）</el-menu-item>
            <el-menu-item index="/process-route">工序路线（曾庆优）</el-menu-item>
          </el-sub-menu>

          <!-- 生产计划管理 -->
          <el-sub-menu index="processManagements">
            <template #title>
              <el-icon>
                <Calendar />
              </el-icon>
              <span>生产计划管理</span>
            </template>
            <el-menu-item index="/GeneratePlan">生产计划（曾庆优）</el-menu-item>
            
          </el-sub-menu>

          <!-- 生产管理 -->
          <el-sub-menu index="Production">
            <template #title>
              <el-icon>
                <Management />
              </el-icon>
              <span>生产管理</span>
            </template>
            <el-menu-item index="/ShenchanInfo">成品生产（曾庆优）</el-menu-item>
            <el-menu-item index="/WorkOrder">工单管理(王文杰)</el-menu-item>
            <el-menu-item index="/Prdu">计划排程(高朋哲)</el-menu-item>
            <el-menu-item index="/Calendar">假期设置(高朋哲)</el-menu-item>
            <el-menu-item index="/Water">天气预报(高朋哲)</el-menu-item>
          </el-sub-menu>

          <!-- 仓库管理 -->
          <el-sub-menu index="Productions">
            <template #title>
              <el-icon>
                <HomeFilled />
              </el-icon>
              <span>仓库管理</span>
            </template>
            <el-menu-item index="/CangKu">仓库信息（胡辉）</el-menu-item>
            <el-menu-item index="/NewCangKu">货架/库存（胡辉）</el-menu-item>
            <el-menu-item index="/CangWei">储存设置（胡辉）</el-menu-item>
            <el-menu-item index="/ScannerView">扫描记录（胡辉）</el-menu-item>
            <el-menu-item index="/CangKuFenPei">入库（胡辉）</el-menu-item>
            <el-menu-item index="/Chuku">出库信息（王文杰）</el-menu-item>
          </el-sub-menu>

          <!-- 发票管理 -->
          <el-sub-menu index="salesinvoices">
            <template #title>
              <el-icon>
                <DocumentCopy />
              </el-icon>
              <span>发票管理</span>
            </template>
            <el-menu-item index="/SalesInvoice">开票信息(高朋哲)</el-menu-item>
            <el-menu-item index="/InvoiceList">到票信息(高朋哲)</el-menu-item>
          </el-sub-menu>

          <!-- 质量管理 -->
          <el-sub-menu index="pro">
            <template #title>
              <el-icon>
                <Document />
              </el-icon>
              <span>质量管理</span>
            </template>
            <el-menu-item index="qualitytypeView">检验类型(王文杰)</el-menu-item>
            <el-menu-item index="qualityproject">检验项目(王文杰)</el-menu-item>
            <el-menu-item index="qualitydesign">检验方案(王文杰)</el-menu-item>
            <el-menu-item index="qualitytask">检验任务(王文杰)</el-menu-item>
            <el-menu-item index="qualitymaterials">来料检验(王文杰)</el-menu-item>
            <el-menu-item index="qualityproduct">成品检验(王文杰)</el-menu-item>
          </el-sub-menu>

          <!-- AI智能客服 -->
          <el-sub-menu index="aiCustomerService">
            <template #title>
              <el-icon>
                <ChatDotRound />
              </el-icon>
              <span>AI智能客服</span>
            </template>
            <el-menu-item index="/ai-customer-service">讯飞AI智能客服（曾庆优）</el-menu-item>
          </el-sub-menu>

          <!-- 系统管理 -->
          <el-sub-menu index="pro1">
            <template #title>
              <el-icon>
                <UserFilled />
              </el-icon>
              <span>系统管理(高朋哲)</span>
            </template>
            <el-menu-item index="GetUser">用户管理</el-menu-item>
            <el-menu-item index="GetRole">角色管理</el-menu-item>
            <el-menu-item index="Factorysa">工厂管理</el-menu-item>
            <el-menu-item index="GetOrcan">组织框架</el-menu-item>
            <el-menu-item index="GetLoginLogger">登录日志</el-menu-item>
          </el-sub-menu>
        </el-menu>
      </div>

      <!-- 右侧主内容区域保持不变 -->
      <div class="right-content">
        <!-- 顶部导航栏 -->
        <div class="top-header">
          <!-- 左侧区域 -->
          <div class="header-left">
            <!-- 汉堡菜单图标 -->
            <el-button type="text" class="hamburger-btn" @click="toggleSidebar">
              <el-icon size="20">
                <Menu />
              </el-icon>
            </el-button>

            <!-- 面包屑导航 -->
            <el-breadcrumb separator="/" class="breadcrumb-nav">
              <!-- 首页面包屑 -->
              <el-breadcrumb-item :to="{ name: 'Index' }">
                <el-icon>
                  <House />
                </el-icon>
                <span>首页</span>
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>

          <!-- 右侧区域 -->
          <div class="header-right">
            <!-- 功能图标组 -->
            <div class="header-icons">
              <!-- 搜索图标 -->
              <el-button type="text" class="icon-btn">
                <el-icon size="18">
                  <Search />
                </el-icon>
              </el-button>

              <!-- 锁定图标 -->
              <el-button type="text" class="icon-btn">
                <el-icon size="18">
                  <Lock />
                </el-icon>
              </el-button>

              <!-- 全屏图标 -->
              <el-button type="text" class="icon-btn">
                <el-icon size="18">
                  <FullScreen />
                </el-icon>
              </el-button>

              <!-- 字体大小图标 -->
              <el-button type="text" class="icon-btn">
                <el-icon size="18">
                  <Document />
                </el-icon>
              </el-button>

              <!-- 通知图标 -->
              <el-button type="text" class="icon-btn notification-btn">
                <el-icon size="18">
                  <Bell />
                </el-icon>
                <el-badge :value="1" class="notification-badge" />
              </el-button>
            </div>

            <!-- 用户信息 -->
            <div class="user-info">
              <span class="company-name">苏州XX电子有限公司</span>
              <span class="user-name">{{ store.Users.userNickname }}</span>
              <el-avatar size="small" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
                class="user-avatar" />
            </div>

            <!-- 设置图标和退出登录 -->
            <div class="header-actions">
              <el-button type="text" class="icon-btn">
                <el-icon size="18">
                  <Sunny />
                </el-icon>
              </el-button>
              <el-button type="text" class="icon-btn">
                <el-icon size="18">
                  <Setting />
                </el-icon>
              </el-button>
              <!-- 退出登录按钮 -->
              <el-button type="text" class="icon-btn logout-btn" @click="handleLogout">
                <el-icon size="18">
                  <ArrowRight />
                </el-icon>
                <span class="logout-text">退出登录</span>
              </el-button>
            </div>
          </div>
        </div>

        <!-- 主内容区域 -->
        <div class="main-content">
          <RouterView />
        </div>
      </div>
    </div>

    <!-- 全局AI聊天组件 -->
    <GlobalAIChat />
  </div>
</template>

<script setup lang="ts">
import { RouterLink, RouterView } from 'vue-router'
import { ref, computed, watch } from 'vue'
import {
  Clock, Box, OfficeBuilding, PriceTag, Link, Star, House, UserFilled, Setting, Menu,
  ArrowDown, Search, Lock, FullScreen, Document, Bell, Sunny, ArrowRight, ChatDotRound,
  Calendar, DocumentCopy
} from '@element-plus/icons-vue'
import GlobalAIChat from '@/components/GlobalAIChat.vue'
import { useRoute, useRouter } from 'vue-router'
import { useCounterStore } from '@/stores/counter';
import { ElMessage } from 'element-plus';

var store = useCounterStore();
const router = useRouter();

// 侧边栏折叠状态
const sidebarCollapsed = ref(false)

// 当前激活的菜单
const activeMenu = ref('dashboard')

// 子菜单展开状态
const openedMenus = ref<string[]>([])

// 路由实例
const route = useRoute()

// 页面标题和描述映射
const pageInfo = {
  dashboard: { title: '仪表盘', description: '系统概览、数据统计、监控面板等' },
  basicData: { title: '基础数据', description: '系统基础数据管理' },
  factoryModeling: { title: '基础数据', description: '工厂结构建模和管理' },
  workshop: { title: '车间管理', description: '车间信息维护和管理' },
  productionLine: { title: '产线管理', description: '生产线配置和管理' },
  workstation: { title: '工位管理', description: '工位设置和配置' },
  materialManagement: { title: '物料管理', description: '物料信息维护' },
  materialGroup: { title: '物料群组', description: '物料分类和群组管理' },
  productMaterial: { title: '产品物料', description: '产品相关物料管理' },
  bom: { title: 'BOM管理', description: '物料清单管理' },
  processManagement: { title: '工序管理', description: '工序路线设计、参数配置、标准制定等' },
  processMaintenance: { title: '工序维护', description: '工序信息维护与管理' },
  processRoute: { title: '工序路线', description: '工序路线设计和配置' },
  processParameter: { title: '工序参数', description: '工序参数设置' },
  processStandard: { title: '工序标准', description: '工序标准制定' },
  qualitytypeView: { title: '检验类型', description: '检验类型管理' },
  qualityproject: { title: '检验项目', description: '检验项目配置' },
  qualitydesign: { title: '检验方案', description: '检验方案设计' },
  qualitytask: { title: '检验任务', description: '检验任务管理' },
  qualitymaterials: { title: '来料检验', description: '来料检验记录' },
  CangKu: { title: '仓库信息', description: '仓库基本信息管理' },
  NewCangKu: { title: '货架/库存', description: '货架和库存管理' },
  ShenchanInfo: { title: '生产信息管理', description: '生产信息的增删改查和统计分析' },
}

// 路径到键名和菜单层级的映射
const pathToKey: Record<string, { key: keyof typeof pageInfo, parentPath?: string, parentName?: string }> = {
  '/CheJian': { key: 'workshop', parentPath: '/basicData', parentName: '基础数据' },
  '/ChanXian': { key: 'productionLine', parentPath: '/basicData', parentName: '基础数据' },
  '/Customer': { key: 'workshop', parentPath: '/basicData', parentName: '基础数据' },
  '/MaterialGroup': { key: 'materialGroup', parentPath: '/basicData', parentName: '基础数据' },
  '/MaterialProduct': { key: 'productMaterial', parentPath: '/basicData', parentName: '基础数据' },
  '/bom': { key: 'bom', parentPath: '/basicData', parentName: '基础数据' },
  '/process-maintenance': { key: 'processMaintenance', parentPath: '/processManagement', parentName: '工艺管理' },
  '/process-route': { key: 'processRoute', parentPath: '/processManagement', parentName: '工艺管理' },
  '/GeneratePlan': { key: 'processManagement', parentPath: '/processManagements', parentName: '生产计划管理' },
  '/CangKu': { key: 'CangKu', parentPath: '/Productions', parentName: '仓库管理' },
  '/NewCangKu': { key: 'NewCangKu', parentPath: '/Productions', parentName: '仓库管理' },
  '/ShenchanInfo': { key: 'ShenchanInfo', parentPath: '/Production', parentName: '生产管理' },
}

// 合并计算属性，减少重复逻辑
const currentPage = computed(() => {
  const key = (pageInfo[activeMenu.value as keyof typeof pageInfo]
    ? (activeMenu.value as keyof typeof pageInfo)
    : pathToKey[activeMenu.value]?.key || 'dashboard')
  return pageInfo[key]
})

// 切换侧边栏
const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

// 子菜单展开处理
const handleSubMenuOpen = (index: string) => {
  if (!openedMenus.value.includes(index)) {
    openedMenus.value.push(index)
  }
}

// 子菜单关闭处理
const handleSubMenuClose = (index: string) => {
  const i = openedMenus.value.indexOf(index)
  if (i > -1) {
    openedMenus.value.splice(i, 1)
  }
}

// 退出登录方法
const handleLogout = async () => {
  try {
    // 清除Pinia中的用户数据
    store.Users.userId = 0;
    store.Users.userNickname = "";
    store.Users.rouleId = 0;
    store.Users.rouleName = "";
    store.Users.Token = "";

    // 清除localStorage和sessionStorage中的数据
    localStorage.removeItem('pinia/counter');
    sessionStorage.removeItem('pinia/counter');

    ElMessage.success('退出登录成功');

    // 跳转到登录页面
    router.push('/');
  } catch (error) {
    console.error('退出登录失败:', error);
    ElMessage.error('退出登录失败，请稍后重试');
  }
}
</script>

<style scoped>
.index-container,
.main-layout {
  display: flex;
  width: 100%;
  height: 100vh;
  margin: 0;
  padding: 0;
}

.index-container {
  /* 移除原有的浅灰色背景，改为与侧边栏相同的浅蓝色渐变 */
  background: linear-gradient(180deg, #e6f7ff 0%, #bae7ff 100%);
}

.main-layout {
  overflow: hidden;
}

/* 侧边栏样式 - 保持现有浅蓝色背景 */
.sidebar {
  width: 280px;
  background: linear-gradient(180deg, #e6f7ff 0%, #bae7ff 100%);
  color: #333333;
  box-shadow: 2px 0 20px rgba(0, 0, 0, 0.1);
  overflow-y: auto;
  transition: width 0.3s ease, box-shadow 0.3s ease;
  flex-shrink: 0;
  position: relative;
}

/* 侧边栏装饰效果 - 调整为适配浅蓝色背景 */
.sidebar::before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 2px;
  height: 100%;
  background: linear-gradient(to bottom, transparent, #1890ff, transparent);
  opacity: 0.3;
}

.sidebar.collapsed {
  width: 64px;
}

/* Logo区域 - 适配浅蓝色背景 */
.logo-section {
  padding: 20px;
  text-align: center;
  border-bottom: 1px solid rgba(24, 144, 255, 0.2);
  min-height: 80px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.5);
  position: relative;
}

.logo-section::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40px;
  height: 3px;
  background: linear-gradient(90deg, transparent, #1890ff, transparent);
}

.logo-icon {
  position: relative;
  width: 40px;
  height: 40px;
  margin: 0 auto 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: radial-gradient(circle, rgba(24, 144, 255, 0.2) 0%, rgba(24, 144, 255, 0) 70%);
  border-radius: 50%;
}

.car-icon {
  font-size: 30px;
  filter: drop-shadow(0 0 10px rgba(24, 144, 255, 0.5));
}

.m-letter {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 18px;
  font-weight: bold;
  color: #1890ff;
  text-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}

.logo-text {
  font-size: 1rem;
  font-weight: 700;
  margin: 0;
  background: linear-gradient(135deg, #1890ff, #0050b3);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  transition: opacity 0.3s ease;
  letter-spacing: 0.5px;
}

/* Element Plus 菜单样式覆盖 - 适配浅蓝色背景 */
.el-menu-vertical {
  border-right: none;
  margin-top: 10px;
  background: transparent !important;
}

/* 菜单项通用样式 - 适配浅蓝色背景 */
.el-menu-vertical .el-menu-item,
.el-menu-vertical .el-sub-menu__title {
  height: 50px;
  line-height: 50px;
  padding: 0 20px;
  margin: 0;
  border-left: 3px solid transparent;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
  color: #333333;
}

/* 菜单项悬停效果 - 适配浅蓝色背景 */
.el-menu-vertical .el-menu-item:hover,
.el-menu-vertical .el-sub-menu__title:hover {
  background: rgba(24, 144, 255, 0.1) !important;
  border-left-color: #1890ff;
  transform: translateX(5px);
  color: #1890ff !important;
}

/* 菜单项激活状态 - 适配浅蓝色背景 */
.el-menu-vertical .el-menu-item.is-active,
.el-menu-vertical .el-sub-menu.is-active .el-sub-menu__title {
  background: rgba(24, 144, 255, 0.2) !important;
  border-left-color: #1890ff;
  color: #1890ff !important;
  font-weight: 500;
}

/* 菜单项激活状态的装饰效果 - 适配浅蓝色背景 */
.el-menu-vertical .el-menu-item.is-active::after,
.el-menu-vertical .el-sub-menu.is-active .el-sub-menu__title::after {
  content: '';
  position: absolute;
  top: 50%;
  right: 10px;
  transform: translateY(-50%);
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #1890ff;
  box-shadow: 0 0 10px rgba(24, 144, 255, 0.7);
}

/* 子菜单样式 - 适配浅蓝色背景 */
.el-menu-vertical .el-menu--inline {
  background: rgba(255, 255, 255, 0.5) !important;
  border-left: 1px solid rgba(24, 144, 255, 0.2);
  margin-left: 15px;
  border-radius: 0 4px 4px 0;
}

.el-menu-vertical .el-menu--inline .el-menu-item {
  padding-left: 55px;
  border-left: 2px solid transparent;
  height: 45px;
  line-height: 45px;
}

/* 子子菜单样式 - 适配浅蓝色背景 */
.el-menu-vertical .el-menu--inline .el-menu--inline {
  background: rgba(255, 255, 255, 0.7) !important;
  border-left: 1px solid rgba(24, 144, 255, 0.1);
}

.el-menu-vertical .el-menu--inline .el-menu--inline .el-menu-item {
  padding-left: 75px;
  border-left: 1px solid transparent;
  height: 40px;
  line-height: 40px;
  font-size: 13px;
  color: #333333;
}

/* 图标样式 - 适配浅蓝色背景 */
.el-menu-vertical .el-icon {
  margin-right: 15px;
  font-size: 18px;
  width: 20px;
  text-align: center;
  transition: transform 0.3s ease;
  color: #333333;
}

.el-menu-vertical .el-menu-item:hover .el-icon,
.el-menu-vertical .el-sub-menu__title:hover .el-icon {
  transform: scale(1.2);
  color: #1890ff;
}

/* 右侧主内容区域 */
.right-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 顶部导航栏 */
.top-header {
  height: 60px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  flex-shrink: 0;
}

/* 左侧区域 */
.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.hamburger-btn,
.icon-btn {
  color: #606266;
  padding: 8px;
}

.hamburger-btn:hover,
.icon-btn:hover {
  color: #409eff;
  background: #f5f7fa;
}

.breadcrumb-nav {
  font-size: 14px;
}

/* 右侧区域 */
.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-icons,
.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.notification-btn {
  position: relative;
}

.notification-badge {
  position: absolute;
  top: 2px;
  right: 2px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 0 16px;
  border-left: 1px solid #e4e7ed;
  border-right: 1px solid #e4e7ed;
}

.company-name {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
}

.user-name {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.user-avatar {
  border: 2px solid #e4e7ed;
}

/* 退出登录按钮样式 */
.logout-btn {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #f56c6c;
  transition: all 0.3s ease;
}

.logout-btn:hover {
  color: #f56c6c;
  background: rgba(245, 108, 108, 0.1);
}

.logout-text {
  font-size: 14px;
}

/* 主内容区域 */
.main-content {
  flex: 1;
  padding: 30px;
  /* 将原有的浅灰色背景改为与侧边栏相同的浅蓝色渐变 */
  background: linear-gradient(180deg, #e6f7ff 0%, #bae7ff 100%);
  overflow-y: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    width: 250px;
  }

  .main-content,
  .content-body {
    padding: 20px;
  }

  .header-right {
    gap: 10px;
  }

  .company-name {
    display: none;
  }
}

@media (max-width: 480px) {
  .top-header {
    padding: 0 10px;
  }

  .header-left {
    gap: 10px;
  }

  .header-right {
    gap: 5px;
  }

  .user-name {
    display: none;
  }

  .main-content {
    padding: 15px;
  }
}
</style>

<style>
/* 全局样式覆盖 */
.el-breadcrumb__inner {
  font-size: 14px;
}

.el-breadcrumb__inner.is-link:hover {
  color: #409eff;
}

.el-icon {
  vertical-align: middle;
}

/* 全局菜单展开/折叠动画优化 */
.el-menu--collapse .el-menu .el-sub-menu {
  min-width: 200px;
}
</style>